package com.xizi.chatBot.controller;

import com.xizi.chatBot.model.ChatInfo;
import com.xizi.chatBot.model.MessageVO;
import com.xizi.chatBot.service.IChatHistoryService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/chat")
@Slf4j
public class ChatController {

//    @Resource(name = "ollamaChatClient")
//    private ChatClient chatClient;

    @Resource(name = "deepSeekChatClient")
    private ChatClient chatClient;

    @Autowired
    private ChatMemory chatMemory;

    @Autowired
    private IChatHistoryService chatHistoryService;

    @RequestMapping(value = "/stream",produces = "text/html;charset=utf-8")
    public Flux<String> stream(String prompt,String chatId) {
        log.info("prompt = {},chatId = {}", prompt,chatId);
        chatHistoryService.save(chatId,prompt);

        return chatClient
                .prompt()
                .user(prompt)
                .advisors(spec -> spec
                        .param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
                .stream()
                .content();
    }

    @RequestMapping(value = "/getChatIds")
    public List<ChatInfo> getChatIds(){
        List<ChatInfo> chatInfos = chatHistoryService.get();
        return chatInfos == null ? new ArrayList<ChatInfo>() : chatInfos;
    }

    @RequestMapping(value = "/getChatHistory")
    public List<MessageVO> getChatHistory(String chatId) {
        log.info("chatId = {}", chatId);
        List<Message> messages = chatMemory.get(chatId, 10);

        if (messages == null) {
            return new ArrayList<>();
        }
        return messages.stream().map(MessageVO::new).toList();
    }

    @RequestMapping("/deleteChat")
    public boolean deleteChat(String chatId) {
        log.info("chatId = {}", chatId);
        try {
            chatMemory.clear(chatId);
            chatHistoryService.clear(chatId);
            return true;
        }catch (Exception e){
            log.error("delete chat error", e);
            return false;
        }
    }
}
